package elka.sag.logisticsystem.actor;

import org.apache.log4j.Logger;

import elka.sag.logisticsystem.bean.ActionStatus;
import elka.sag.logisticsystem.bean.Order;
import elka.sag.logisticsystem.bean.Order.OrderStatus;
import elka.sag.logisticsystem.message.SimpleMessage;

public class NotificationActor extends BaseActor {
	private static final String RULE_PATH = "notificationRules.drl";	
	private static final String BROKEN_NOTIFICATION = "BROKEN_NOTIFICATION";
	
	private final static Logger LOGGER = Logger.getLogger(NotificationActor.class);
	

	@Override
	public void preStart() {
		super.preStart();
		ruleService.loadRules(RULE_PATH, getClass().getName());
	}
	
	@Override
	protected void processMessage(SimpleMessage message) throws Exception {
		//dla symulacji przetwarzania czekamy przez losowy czas 0-10s
		int waitForTime = (int) (Math.random() * 1500);
		Thread.sleep(waitForTime);
		
		LOGGER.info("Notyfikacja o skompletowaniu zamowienia, orderId: " + message.getOrderId());
		Order order = repositoryService.getOrderById(message.getOrderId());
		
		String param = repositoryService.getParam(BROKEN_NOTIFICATION);
		
		ActionStatus actionStatus = ActionStatus.OK;
		if("Y".equals(param)) {
			actionStatus = ActionStatus.ERROR_NOTIFICATION;
		}
		
		OrderStatus newStatus = getNextOrderStatus(order, actionStatus);
		
		order.setStatus(newStatus);
		order.setProcess(false);
		//tylko zapisanie informacji o nowym statusie
		repositoryService.updateOrderStatusAndProcess(order);
	}

}
